import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Form, Input, Button, Card, message, Select } from 'antd';
import { history, useParams } from 'umi';

const { Option } = Select;
const { TextArea } = Input;

const PermissionEditPage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [initialLoading, setInitialLoading] = useState(true);
  const [permissionType, setPermissionType] = useState('menu');
  const { id } = useParams<{ id: string }>();

  useEffect(() => {
    const fetchPermission = async () => {
      try {
        // TODO: Replace with actual API call
        // const response = await fetch(`/api/permissions/${id}`);
        // const data = await response.json();
        
        // Mock data for now
        const mockData = {
          id: id,
          name: '权限管理',
          code: 'permission:manage',
          type: 'menu',
          path: '/permission',
          status: 1,
          description: '权限管理菜单',
        };
        
        form.setFieldsValue(mockData);
        setPermissionType(mockData.type);
      } catch (error) {
        message.error('获取权限信息失败');
      } finally {
        setInitialLoading(false);
      }
    };

    if (id) {
      fetchPermission();
    } else {
      setInitialLoading(false);
    }
  }, [id, form]);

  const onFinish = async (values: any) => {
    setLoading(true);
    try {
      // TODO: Replace with actual API call
      // await fetch(`/api/permissions/${id}`, {
      //   method: 'PUT',
      //   headers: {
      //     'Content-Type': 'application/json',
      //   },
      //   body: JSON.stringify(values),
      // });
      
      message.success('权限更新成功');
      history.push('/permission/list');
    } catch (error) {
      message.error('权限更新失败');
    } finally {
      setLoading(false);
    }
  };

  const handleTypeChange = (value: string) => {
    setPermissionType(value);
  };

  if (initialLoading) {
    return <div>加载中...</div>;
  }

  return (
    <PageContainer
      header={{
        title: '编辑权限',
        breadcrumb: {
          items: [
            { title: '系统管理' },
            { title: '权限管理', path: '/permission/list' },
            { title: '编辑权限' },
          ],
        },
      }}
    >
      <Card>
        <Form
          form={form}
          layout="vertical"
          onFinish={onFinish}
        >
          <Form.Item name="id" hidden>
            <Input type="hidden" />
          </Form.Item>

          <Form.Item
            name="name"
            label="权限名称"
            rules={[{ required: true, message: '请输入权限名称' }]}
          >
            <Input placeholder="请输入权限名称" />
          </Form.Item>

          <Form.Item
            name="code"
            label="权限标识"
            rules={[
              { required: true, message: '请输入权限标识' },
              {
                pattern: /^[a-zA-Z0-9:]+$/,
                message: '只能包含字母、数字和冒号',
              },
            ]}
          >
            <Input placeholder="如：user:create" disabled={true} />
          </Form.Item>

          <Form.Item
            name="type"
            label="权限类型"
            rules={[{ required: true, message: '请选择权限类型' }]}
          >
            <Select onChange={handleTypeChange} disabled={true}>
              <Option value="menu">菜单</Option>
              <Option value="button">按钮</Option>
              <Option value="api">接口</Option>
            </Select>
          </Form.Item>

          {permissionType === 'menu' && (
            <Form.Item
              name="path"
              label="菜单路径"
              rules={[{ required: true, message: '请输入菜单路径' }]}
            >
              <Input placeholder="如：/system/user" />
            </Form.Item>
          )}

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select>
              <Option value={1}>启用</Option>
              <Option value={0}>禁用</Option>
            </Select>
          </Form.Item>

          <Form.Item name="description" label="描述">
            <TextArea rows={4} placeholder="请输入权限描述" />
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" loading={loading}>
              保存
            </Button>
            <Button
              style={{ marginLeft: 8 }}
              onClick={() => history.goBack()}
              disabled={loading}
            >
              返回
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};

export default PermissionEditPage;
